/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bmechat.gui;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import bmechat.client.Client;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JSeparator;

/**
 *
 * @author david
 */
public class ClientFrame extends JFrame {

    private Client client;
    private JPanel listPanel, logPanel, inputPanel;
    private JTextArea input;

    public ClientFrame(String name, String serverName, int serverPort) {
        super("BME-Chat");
        client = new Client(name, serverName, serverPort);
        ExecutorService pool = Executors.newFixedThreadPool(1);
        pool.execute(client);

        initFrame();
    }

    private void initFrame() {
        JPanel cp = new JPanel();
        cp.setLayout(new BorderLayout(10, 10));
        cp.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        initLogPanel();
        initListPanel();
        initInputPanel();

        cp.add(logPanel, BorderLayout.CENTER);
        cp.add(listPanel, BorderLayout.EAST);
        cp.add(inputPanel, BorderLayout.SOUTH);

        Container contentPane = getContentPane();
        contentPane.add(cp);
        this.setJMenuBar(generateMenu());
        pack();
        input.requestFocus();
        this.setExtendedState(this.getExtendedState() | JFrame.MAXIMIZED_BOTH);
        setVisible(true);
    }

    private void initListPanel() {
        listPanel = new JPanel(new BorderLayout(10, 10));
        listPanel.setPreferredSize(new Dimension(150, 500));
        JList listOfClients = new JList(client);
        JLabel clients = new JLabel("Users", JLabel.CENTER);
        listPanel.add(clients, BorderLayout.NORTH);
        listPanel.add(listOfClients, BorderLayout.CENTER);
    }

    private void initLogPanel() {
        logPanel = new JPanel(new BorderLayout(10, 10));
        logPanel.setPreferredSize(new Dimension(550, 500));

        JTextArea logArea = new ChatLogArea(client);
        JScrollPane scrollPane = new JScrollPane(logArea);
        logPanel.add(scrollPane, BorderLayout.CENTER);
    }

    private void initInputPanel() {
        inputPanel = new JPanel(new BorderLayout(5, 5));
        inputPanel.setPreferredSize(new Dimension(700, 30));

        input = new JTextArea();
        input.addKeyListener(new java.awt.event.KeyAdapter() {

            public void keyReleased(java.awt.event.KeyEvent evt) {
                inputKeyReleased(evt);
            }
        });
        inputPanel.add(input, BorderLayout.CENTER);

        JButton submit = new JButton();
        submit.setText("Submit");
        submit.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent evt) {
                submitActionPerformed(evt);
            }
        });
        inputPanel.add(submit, BorderLayout.EAST);
    }

    private JMenuBar generateMenu() {
        JMenuBar menu = new JMenuBar();

        JMenu file = new JMenu("File");
        JMenuItem admin = new JMenuItem("Admin login");
        admin.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                adminActionPerformed(evt);
            }
        });
        JMenuItem kick = new JMenuItem("Kick user");
        kick.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                kickActionPerformed(evt);
            }
        });
        JMenuItem rename = new JMenuItem("Rename");
        rename.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                renameActionPerformed(evt);
            }
        });
        JMenuItem reconnect = new JMenuItem("Reconnect");
        reconnect.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                reconnectActionPerformed(evt);
            }
        });
        JMenuItem exit = new JMenuItem("Exit");
        exit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK));
        exit.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitActionPerformed(evt);
            }
        });
        JSeparator fs1 = new JSeparator();
        JSeparator fs2 = new JSeparator();
        file.add(admin);
        file.add(kick);
        file.add(fs1);
        file.add(rename);
        file.add(reconnect);
        file.add(fs2);
        file.add(exit);
        menu.add(file);

        JMenu extra = new JMenu("Extra");
        JMenuItem calc = new JMenuItem("Calculate...");
        calc.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                calcActionPerformed(evt);
            }
        });
        JMenuItem google = new JMenuItem("Google search");
        google.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                googleActionPerformed(evt);
            }
        });
        JMenuItem russroul = new JMenuItem("Russian Roullette");
        russroul.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                russroulActionPerformed(evt);
            }
        });
        JMenuItem filetransfer = new JMenuItem("File transfer");
        filetransfer.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                filetransferActionPerformed(evt);
            }
        });
        JSeparator es1 = new JSeparator();
        JSeparator es2 = new JSeparator();
        extra.add(calc);
        extra.add(google);
        extra.add(es1);
        extra.add(russroul);
        extra.add(es2);
        extra.add(filetransfer);
        menu.add(extra);

        return menu;
    }

    private void inputKeyReleased(KeyEvent evt) {
        // TODO add your handling code here:
        if (input.isFocusOwner()) {
            if (evt.getKeyCode() == evt.VK_ENTER) {
                if(this.input.getText().indexOf("\n")!=-1)
                {
                    client.sendMessage(this.input.getText().substring(0, this.input.getText().indexOf("\n")));
                    this.input.setText("");
                }
            }
        }
    }

    private void submitActionPerformed(ActionEvent evt) {
        client.sendMessage(this.input.getText());
        input.setText("");
    }

    private void exitActionPerformed(ActionEvent evt) {
        int quit = JOptionPane.showConfirmDialog(this, "By quitting, all connections will be closed.\nAre you sure you want to quit?",
                "Confirm Action", JOptionPane.YES_NO_OPTION);
        if (quit == JOptionPane.YES_OPTION) {
            this.dispose();
            System.exit(0);
        }
    }

    private void renameActionPerformed(ActionEvent evt) {
        String userInput = JOptionPane.showInputDialog(this, "Please provide a new nickname");
        if(userInput!=null)
            client.sendMessage("#name = " + userInput);
    }

    private void reconnectActionPerformed(ActionEvent evt) {
        try {
            ExecutorService pool = Executors.newFixedThreadPool(1);
            pool.execute(client);
        } catch (Exception ex) {
            client.addToChatLog("Could not reconnect. Please try rebooting the program.");
        }
    }

    private void adminActionPerformed(ActionEvent evt) {
        String userInput = JOptionPane.showInputDialog("Please provide us with the password of your server.");
        if(userInput!=null)
            client.sendMessage("#password =" + userInput);
    }

    private void kickActionPerformed(ActionEvent evt) {
        String userInput = JOptionPane.showInputDialog("Please enter a username.");
        if(userInput!=null)
            client.sendMessage("#kick = " + userInput);
    }

    private void calcActionPerformed(ActionEvent evt) {
        String userInput = JOptionPane.showInputDialog("Please enter your equation.");
        if(userInput!=null)
            client.sendMessage("#calc = " + userInput);
    }

    private void googleActionPerformed(ActionEvent evt) {
        String userInput = JOptionPane.showInputDialog("Please enter what you are looking for.");
        if(userInput!=null)
            client.sendMessage("#google=" + userInput);
    }

    private void russroulActionPerformed(ActionEvent evt) {
        String userInput = JOptionPane.showInputDialog("Please enter the name of your opponent.");
        if(userInput!=null)
            client.sendMessage("#rr=" + userInput);
    }

    private void filetransferActionPerformed(ActionEvent evt) {
        try {
            JFileChooser filechooser = new JFileChooser();
            filechooser.setVisible(true);
            filechooser.grabFocus();
            filechooser.setMultiSelectionEnabled(false);
            File file;
            int option = filechooser.showOpenDialog(ClientFrame.this);
            if (option == JFileChooser.APPROVE_OPTION) {
                file = filechooser.getSelectedFile();

                client.setFile(file);
                String userInput = JOptionPane.showInputDialog("Please enter the recipients name.");
                if(userInput!=null)
                    client.sendMessage("#filetransfer = " + userInput + "\\" + file.length() + "/" + client.getIName() + '*' + file.getName());
                else
                    client.addToChatLog("You canceled the file transfer.");
            } else {
                client.addToChatLog("You canceled the file transfer.");
            }
        } catch (Exception ex) {
            client.addToChatLog("Filetransfer failed.");
        }
    }
}
